package com.renchunlin.myapplication.utils;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static java.lang.String.valueOf;

/*
 *  *- get
 *  - post
 *  - post file
 *  *- download
 */

public class OkHttpUtils {

    private static android.os.Handler mHandler = new android.os.Handler();
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    public static void get(String url, final OnOkHttpCallback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String json = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccessful(json);
                        }
                    });
                } else {
                    callback.onFailure("response not isSuccessful");
                }
            }
        });
    }

    public static void post(String url, Headers headers, Map<String, String> params, final OnOkHttpCallback callback) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder form = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        /*Headers headers = new Headers.Builder()
                .add("User-Agent", "okhttpclient")
                .add("Host", "baidu.com")
                .build();*/

        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(form.build())
                .build();


        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String json = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccessful(json);
                        }
                    });
                } else {
                    callback.onFailure("response not isSuccessful");
                }
            }
        });
    }

    public static void post_file(Context mContext, final String url/*, final Map<String, Object> map*/, String file, final OnOkHttpCallback callback) {
        File file1 = new File(file);
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image/jpeg"), file1);
            String filename = file1.getName();
            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart("logo", file1.getName(), body);
        }
        /*if (map != null) {
            // map 里面是请求中所需要的 key 和 value
            for (Map.Entry entry : map.entrySet()) {
                requestBody.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
            }
        }*/
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody.build())
                .tag(mContext)
                .build();
        // readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String str = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccessful(str);
                        }
                    });
                } else {
                    callback.onFailure("response not isSuccessful");
                }
            }
        });

    }

    public static void download(final String path, String url
            , final OnOkHttpCallback callback
            , final OnProgressResponseListener responseListener) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    InputStream is = response.body().byteStream();
                    //总长度
                    long total = response.body().contentLength();
                    //路径
                    File file = new File(path);
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] buf = new byte[2048];
                        //记录下载的进度
                        int sum = 0;
                        int len = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0000, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            responseListener.OnProgressResponse(progress, total);
                        }
                        fos.flush();
                        fos.close();
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccessful("done");
                            }
                        });
                    } catch (final IOException e) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFailure(e);
                            }
                        });
                    }

                } else {
                    callback.onFailure("response not isSuccessful");
                }
            }
        });
    }

    public interface OnProgressResponseListener {

        void OnProgressResponse(int progress, long total);
    }

    public interface OnOkHttpCallback {
        //失败
        void onFailure(IOException e);

        //请求成功，但是没有结果
        void onFailure(String msg);

        //成功
        void onSuccessful(String json);
    }
}
